
package com.wy2cloud.core.web.filter;

import org.springframework.util.StringUtils;

import com.wy2cloud.core.tools.HttpServletUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * 系统名称 xx平台
 * 工程名称 ioop-cloud
 * 创建时间 2017/6/8 15:48
 * 服务相对于服务网关 前缀路径处理过滤器
 * @author wuyy
 * @since 1.8
 */
public class PrefixPathHandleFilter implements Filter {
    /**
     * 默认Order
     */
    public static final int DEFAULT_ORDER = Integer.MAX_VALUE -100;

    public static final String ATTR_NAME="prefixPath";
    private static final String Default_Context_Path="/";

    public static final String getPrefixPath(HttpServletRequest request){
        Object obj=  request.getAttribute(PrefixPathHandleFilter.ATTR_NAME);
        String prefixPath="";
        if(obj!=null){
            prefixPath=(String) obj;
        }
        return prefixPath;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        String contextPath=req.getContextPath();

        //取zuul下发的proxy-header信息
        String prefixPath= HttpServletUtils.getZuulPrefix(req,true);
        if(prefixPath!=null){
            if(!Default_Context_Path.equals(contextPath)){
                prefixPath+=contextPath;
            }
            req.setAttribute(ATTR_NAME,prefixPath);
        }else{
            prefixPath="";
            if(!Default_Context_Path.equals(contextPath)){
                prefixPath+=contextPath;
            }
            req.setAttribute(ATTR_NAME,prefixPath);
        }
        /*Enumeration<String> names = req.getAttributeNames();
        while (names.hasMoreElements()){
            System.out.println("Name:"+names.nextElement());
        }*/

        chain.doFilter(request, response);

    }

    @Override
    public void destroy() {

    }


}